package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 菜品管理
 */
@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 添加菜品
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());
        dishService.saveWithFlavors(dishDto);

        //清楚缓存方式
        //1.全局清理 dish_*
        //Set keys = redisTemplate.keys("dish_*");
        //redisTemplate.delete(keys);
        //2.精准清理
        redisTemplate.delete("dish_" + dishDto.getCategoryId() + "_1");

        return R.success("新增菜品成功");
    }

    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        //一,菜品基础分页查询
        //分页构建器
        Page<Dish> dishPage = new Page<>(page, pageSize);

        //条件构建器
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.like(StringUtils.isNotEmpty(name), Dish::getImage, name);
        lqw.orderByDesc(Dish::getUpdateTime);
        //查询
        dishService.page(dishPage, lqw);

        //二,处理分页集合数据
        Page<DishDto> dishDtoPage = new Page<>();
        //1.复制分页信息(排除分页集合数据，数据不对(没有分类名称))
        BeanUtils.copyProperties(dishPage, dishDtoPage, "records");
        //2.单独出来集合数据
        //a.获取原始dishPage分页对象中集合数据
        List<Dish> records = dishPage.getRecords();

        ArrayList<DishDto> dtoList = new ArrayList<>();

        //b.遍历集合
        records.forEach(dish -> {
            //创建一个DishDto对象
            DishDto dishDto = new DishDto();
            //复制dish数据到dishDto
            BeanUtils.copyProperties(dish, dishDto);
            //查询分类名称
            Category category = categoryService.getById(dish.getCategoryId());
            //设置分类名称到dishDto中
            if (category != null) {
                dishDto.setCategoryName(category.getName());
            }
            dtoList.add(dishDto);
        });
        //将处理后的集合，添加到分页对象
        dishDtoPage.setRecords(dtoList);

        return R.success(dishDtoPage);

    }

    /**
     * 根据id查询菜品信息和对应的口味信息(回显)
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id) {
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 更新菜品信息，同时更新对应的口味信息
     *
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());

        dishService.updateWithFlavor(dishDto);

        //清楚缓存方式
            //1.全局清理 dish_*
        //Set keys = redisTemplate.keys("dish_*");
        //redisTemplate.delete(keys);
            //2.精准清理
        redisTemplate.delete("dish_" + dishDto.getCategoryId() + "_1");

        return R.success("修改菜品成功");
    }

    /**
     * 删除菜品信息，同时删除对应的口味信息
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids) {

        log.info(ids.toString());

        dishService.removeByIdWithFlavor(ids);

        for (Long id : ids) {
            //清楚缓存方式
            //1.全局清理 dish_*
            //Set keys = redisTemplate.keys("dish_*");
            //redisTemplate.delete(keys);
            //2.精准清理
            redisTemplate.delete("dish_" + id + "_1");
        }

        return R.success("删除菜品成功!");
    }

    /**
     * 修改status状态
     * @param type
     * @param ids
     * @return
     */
    @PostMapping("/status/{type}")
    public R<String> updateStatus(@PathVariable Integer type, Long[] ids) {
        for (Long id : ids) {
            Dish dish = dishService.getById(id);
            if (type == 0){
                dish.setStatus(0);
                //清楚缓存方式
                //1.全局清理 dish_*
                //Set keys = redisTemplate.keys("dish_*");
                //redisTemplate.delete(keys);
                //2.精准清理
                redisTemplate.delete("dish_" + id + "_1");
        }else{
            dish.setStatus(1);
                //清楚缓存方式
                //1.全局清理 dish_*
                //Set keys = redisTemplate.keys("dish_*");
                //redisTemplate.delete(keys);
                //2.精准清理
                redisTemplate.delete("dish_" + id + "_1");

        }
            dishService.save(dish);
    }

        return R.success("修改状态成功");
    }

    /**
     * 套餐管理，根据条件查询菜品
     * @param dish
     * @return
     */
    /*@GetMapping("/list")
    public R<List<Dish>> list(Dish dish){
        //条件构建器
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(dish.getCategoryId() != null,Dish::getCategoryId,dish.getCategoryId());
        //添加条件，查询状态为1的(起售)
        lqw.eq(Dish::getStatus,1);
        lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        //查询
        List<Dish> list = dishService.list(lqw);
        return R.success(list);
    }*/


    /**
     * 套餐管理，根据条件查询菜品(移动端显示)
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){

        //查询redis缓存
        String key = "dish_" + dish.getCategoryId() + "_1";
        List<DishDto> dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);

        //判断缓存是否有数据
            //若有，直接返回缓存数据
        if (dishDtoList != null){
            return R.success(dishDtoList);
        }
            //若没有，查询数据库

        //查询菜品集合
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(dish.getCategoryId() != null,Dish::getCategoryId,dish.getCategoryId());
        lqw.eq(Dish::getStatus,1);
        lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(lqw);

        //复制Dish-->DishDto
        ArrayList<DishDto> dtoList = new ArrayList<>();

        //b.遍历集合
        list.forEach(d -> {
            //创建一个DishDto对象
            DishDto dishDto = new DishDto();
            //复制dish数据到dishDto
            BeanUtils.copyProperties(d, dishDto);
            //查询菜品口味数据
            LambdaQueryWrapper<DishFlavor> las = new LambdaQueryWrapper<>();
            las.eq(DishFlavor::getDishId,d.getId());
            List<DishFlavor> flavorList = dishFlavorService.list(las);
            dishDto.setFlavors(flavorList);

            dtoList.add(dishDto);

        });

        //将查询的数据，放入缓存
        redisTemplate.opsForValue().set(key,dtoList);
        return R.success(dtoList);
    }

}